/**
 * Huisou.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */

package com.lyqg.biz;

import static com.core.Constants.STATUS_DELETED;
import static com.core.Constants.STATUS_NORMAL;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.core.orm.Page;
import com.core.orm.PageRequest;
import com.lyqg.dao.MessageDao;
import com.lyqg.domain.Message;
import com.lyqg.domain.User;

/**
 * @description
 * 
 * @author chenzehe
 * @email hljuczh@163.com
 * @create 2012-8-14 下午09:00:35
 */
@Service
@Transactional
public class MessageService extends BaseService implements IMessageService {
	@Resource
	MessageDao messageDao;
	@Resource
	IContentService contentService;
	@Resource
	IFxService fxService;
	@Resource
	IJyService jyService;

	@Override
	public void save(Message message) {
		messageDao.save(message);
		if (message.getType() == Message.MessageType.CONTENT.type()) {
			contentService.updateCommentCount(message.getContentId());
		} else if (message.getType() == Message.MessageType.FX.type()) {
			fxService.updateCommentCount(message.getContentId());
		} else if (message.getType() == Message.MessageType.JY.type()) {
			jyService.updateCommentCount(message.getContentId());
		}
	}

	@Override
	public Page<Message> queryByContentId(PageRequest pageRequest, int type,
			int contentId) {
		String sql = "SELECT m.id,m.msg,m.content_id,m.issue_time,m.type,m.ding,m.cai,u.id AS uid,u.username,u.point FROM tbl_message m LEFT JOIN tbl_user u ON m.user_id = u.id WHERE m.content_id=? AND m.type=? AND m.status=? ORDER BY m.issue_time DESC LIMIT ?,?";
		Object[] paramsObjects = new Object[] { contentId, type, STATUS_NORMAL,
				(pageRequest.getPageNo() - 1) * pageRequest.getPageSize(),
				pageRequest.getPageSize() };
		List<Message> listMessage = jdbcTemplate.query(sql, paramsObjects,
				new RowMapper<Message>() {
					public Message mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						return initMessageUser(rs);
					}
				});
		String countSql = "SELECT COUNT(*) FROM tbl_message m LEFT JOIN tbl_user u ON m.user_id = u.id WHERE m.content_id=? AND m.type=? AND m.status=?";
		Long count = jdbcTemplate.queryForLong(countSql, contentId, type,
				STATUS_NORMAL);
		Page<Message> pageMessage = new Page<Message>(pageRequest);
		pageMessage.setTotalItems(count);
		pageMessage.setResult(listMessage);
		return pageMessage;
	}

	@Override
	public Page<Message> queryByUserIdAndType(PageRequest pageRequest,
			int userId, int type) {
		StringBuilder sql = new StringBuilder(
				"SELECT m.id,m.msg,m.content_id,m.issue_time,m.type,o.title,o.img FROM tbl_message m LEFT JOIN ");
		if (type == Message.MessageType.CONTENT.type()) {
			sql.append("tbl_content o");
		} else if (type == Message.MessageType.FX.type()) {
			sql.append("tbl_fx o");
		} else if (type == Message.MessageType.JY.type()) {
			sql.append("tbl_jy o");
		}
		sql.append(" ON m.content_id=o.id WHERE m.user_id=? AND m.type=? AND m.status=? ORDER BY m.id DESC LIMIT ?,?");
		Object[] paramsObjects = new Object[] { userId, type, STATUS_NORMAL,
				(pageRequest.getPageNo() - 1) * pageRequest.getPageSize(),
				pageRequest.getPageSize() };

		List<Message> listMessage = jdbcTemplate.query(sql.toString(),
				paramsObjects, new RowMapper<Message>() {
					public Message mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						return initMessage(rs);
					}
				});
		Page<Message> pageMessage = new Page<Message>(pageRequest);
		String countSql = "SELECT COUNT(*) FROM tbl_message WHERE user_id=? AND type=? AND status=?";
		Long count = jdbcTemplate.queryForLong(countSql, userId, type,
				STATUS_NORMAL);
		pageMessage.setTotalItems(count);
		pageMessage.setResult(listMessage);
		return pageMessage;
	}

	private Message initMessage(ResultSet rs) throws SQLException {
		Message message = new Message();
		message.setId(rs.getInt("id"));
		message.setContentId(rs.getInt("content_id"));
		message.setMessage(rs.getString("msg"));
		message.setContent(rs.getString("title"));
		message.setImg(rs.getString("img"));
		message.setIssueTime(rs.getTimestamp("issue_time"));
		message.setType(rs.getInt("type"));
		return message;
	}

	private Message initMessageUser(ResultSet rs) throws SQLException {
		Message message = new Message();
		message.setId(rs.getInt("id"));
		message.setContentId(rs.getInt("content_id"));
		message.setMessage(rs.getString("msg"));
		message.setIssueTime(rs.getTimestamp("issue_time"));
		message.setType(rs.getInt("type"));
		message.setDing(rs.getInt("ding"));
		message.setCai(rs.getInt("cai"));
		message.setUserId(rs.getInt("uid"));
		User user = new User();
		user.setId(rs.getInt("uid"));
		user.setUsername(rs.getString("username"));
		user.setPoint(rs.getInt("point"));
		message.setUser(user);
		return message;
	}

	@Override
	public void deleteByIdAndUser(int id, int userId) {
		String hql = "UPDATE Message SET status=? WHERE id=? AND userId=?";
		messageDao.batchExecute(hql, STATUS_DELETED, id, userId);
	}

	@Override
	public Long queryMessaageNumByUser(int userId) {
		String sql = "SELECT COUNT(*) FROM tbl_message WHERE user_id=? AND status=?";
		return jdbcTemplate.queryForLong(sql, userId, STATUS_NORMAL);
	}

	@Override
	public void updateDing(int id) {
		String hql = "UPDATE Message SET ding=ding+1 WHERE id=?";
		messageDao.batchExecute(hql, id);
	}

	@Override
	public void updateCai(int id) {
		String hql = "UPDATE Message SET cai=cai+1 WHERE id=?";
		messageDao.batchExecute(hql, id);
	}

}
